package nosdk;

import org.apache.dubbo.common.Constants;
import org.apache.dubbo.common.beanutil.JavaBeanDescriptor;
import org.apache.dubbo.common.beanutil.JavaBeanSerializeUtil;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.common.io.UnsafeByteArrayInputStream;
import org.apache.dubbo.common.io.UnsafeByteArrayOutputStream;
import org.apache.dubbo.common.json.JSON;
import org.apache.dubbo.common.serialize.Serialization;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ReferenceConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.rpc.service.GenericService;

import java.io.IOException;
import java.io.Serializable;

/**
 * Copyright (c)  by www.leya920.com
 * All right reserved.
 * Create Date: 2020-11-21 18:19
 * Create Author: xuweiwei
 * File Name: ApiGenericConsumerForTrue.java
 * Last version:  1.0
 * Function: //TODO
 * Last Update Date: 2020-11-21 18:19
 * Last Update Log:
 * Comment: //TODO
 **/
public class ApiGenericConsumerForNativeJava {

    public static void main(String[] args) throws IOException, ClassNotFoundException {


        // 1 GenericService
        ReferenceConfig<GenericService> referenceConfig = new ReferenceConfig<>();

        // 2 设置应用程序信息
        referenceConfig.setApplication(new ApplicationConfig("first-dubbo-consumer"));

        // 3 设置服务注册中心
        referenceConfig.setRegistry(new RegistryConfig("zookeeper://127.0.0.1:2181"));

        // 4 设置服务接口  超时时间
        referenceConfig.setInterface("api.GreetingService");
        // 5 设置泛化引用为true
        referenceConfig.setGeneric("nativejava");
        // 6 超时时间
        referenceConfig.setTimeout(5000);

        // 7 设置服务分子与版本
        referenceConfig.setGroup("dubbo");
        referenceConfig.setVersion("1.0.0");

        // 8 引用服务  用GenericService 代替所有的接口引用
        GenericService greetingService = referenceConfig.get();
        UnsafeByteArrayOutputStream out = new UnsafeByteArrayOutputStream();

        // 9 泛型调用  需要吧参数使用java序列化为二进制
        ExtensionLoader.getExtensionLoader(Serialization.class)
                .getExtension(Constants.GENERIC_SERIALIZATION_NATIVE_JAVA)
                .serialize(null, out)
                .writeObject("native dubbo world");


        Object result = greetingService.$invoke("sayHello", new String[]{"java.lang.String"}, new Object[]{out.toByteArray()});


        UnsafeByteArrayInputStream in  = new UnsafeByteArrayInputStream((byte[])result);
        System.out.println(ExtensionLoader.getExtensionLoader(Serialization.class)
                .getExtension(Constants.GENERIC_SERIALIZATION_NATIVE_JAVA)
                .deserialize(null, in)
                .readObject());

    }
}
